package com.heima.wemedia.service.impl;

import com.alibaba.nacos.common.utils.Md5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.wmmedia.dtos.WmUserDTO;
import com.heima.model.wmmedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    //根据用户名查询自媒体用户
    @Override
    public ResponseResult findByName(String name) {
        //非空判断
        if (StringUtils.isBlank(name)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据name查询用户
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.lambdaQuery();
        //设置查询条件
        wrapper.eq(WmUser::getName, name);
        //查询
        WmUser wmUser = wmUserMapper.selectOne(wrapper);
        //对集合非空判断
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "没有WmUser数据!");
        }
        //有数据,返回给前端
        return ResponseResult.okResult(wmUser);
    }

    //保存自媒体用户
    @Override
    public ResponseResult insert(WmUser wmUser) {
        System.err.println("wmUser = " + wmUser);
        //非空判断
        if (wmUser == null || StringUtils.isBlank(wmUser.getApUserId().toString())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分别根据用户id查询是否存在数据
        LambdaQueryWrapper<WmUser> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(WmUser::getApUserId, wmUser.getApUserId());
        List<WmUser> wmUsers1 = wmUserMapper.selectList(wrapper1);
        //判断
        if (wmUsers1.size() != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //判断是否存在作者id
        if (wmUser.getApAuthorId() != null) {
            //有作者id
            //根据作者id查询是否存在数据
            LambdaQueryWrapper<WmUser> wrapper2 = Wrappers.lambdaQuery();
            wrapper2.eq(WmUser::getApAuthorId, wmUser.getApAuthorId());
            List<WmUser> wmUsers2 = wmUserMapper.selectList(wrapper2);
            if (wmUsers2.size() != 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
            }
        }
        //数据不存在,可以保存
        wmUser.setCreatedTime(new Date());
        if (wmUserMapper.insert(wmUser) != 1) {
            //添加失败
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        //返回wmUser,方便user调用时可以获取wmuser_id
        return ResponseResult.okResult(wmUser);
    }

    //自媒体用户登录
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //非空判断
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询数据库
        LambdaQueryWrapper<WmUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmUser::getName, dto.getName());
        WmUser wmUser = wmUserMapper.selectOne(wrapper);
        //判断是否存在该用户
        if (wmUser == null) {
            //不存在该用户,提示错误
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该用户不存在!");
        }
        //存在该用户,使用MD5混合加密,对用户输入的密码进行加密
        String md5 = Md5Utils.getMD5((dto.getPassword() + wmUser.getSalt()).getBytes());
        //判断该md5和数据库密码是否一致
        if (!wmUser.getPassword().equals(md5)) {
            //密码不一致,提示错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_NameOrPASSWORD_ERROR);
        }
        //密码正确,判断用户状态
        if (wmUser.getStatus() != 9) {
            //用户状态异常
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //更新用户登陆时间
        wmUser.setLoginTime(new Date());
        wmUserMapper.updateById(wmUser);
        //用户状态正常,生成token
        String token = AppJwtUtil.getToken(Long.parseLong(wmUser.getId().toString()));
        //封装数据
        WmUserVO wmUserVO = new WmUserVO();
        try {
            BeanUtils.copyProperties(wmUser, wmUserVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //创建集合,保存用户数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", wmUserVO);
        //返回数据
        return ResponseResult.okResult(map);
    }
}
